package com.ideaaedi.springcloud.jd.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ideaaedi.springcloud.jd.commonds.entity.PageInfo;
import com.ideaaedi.springcloud.jd.commonds.entity.user.po.SysAkskUserPO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysAkskUserAddReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysAkskUserListReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysAkskUserUpdateReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysUserAddReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.req.SysUserUpdateReqVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysAkskUserDetailRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysAkskUserListRespVO;
import com.ideaaedi.springcloud.jd.commonds.entity.user.vo.resp.SysUserDetailRespVO;
import com.ideaaedi.springcloud.jd.commonds.enums.user.UserTypeEnum;
import com.ideaaedi.springcloud.jd.commonspring.mybatisplus.ServiceImplExt;
import com.ideaaedi.springcloud.jd.user.mapper.SysAkskUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统-aksk用户 服务实现类
 * </p>
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.5.B
 */
@Service
public class SysAkskUserServiceImpl extends ServiceImplExt<SysAkskUserMapper, SysAkskUserPO> implements SysAkskUserService {

    @Resource
    private SysUserService sysUserService;
    
    @Nullable
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAkskUserDetailRespVO add(SysAkskUserAddReqVO req, boolean queryDetail) {
        String tenant = req.getTenant();
        String accessKey = req.getAccessKey();
        String secretKey = req.getSecretKey();
        String orgName = req.getOrgName();
    
        // 存sys_user
        SysUserAddReqVO sysUserAddReq = new SysUserAddReqVO();
        sysUserAddReq.setTenant(tenant);
        sysUserAddReq.setType(UserTypeEnum.CLIENT_AK_SK);
        sysUserAddReq.setAccountNo(accessKey);
        sysUserAddReq.setPassword(secretKey);
        sysUserAddReq.setName(orgName);
        SysUserDetailRespVO sysUserDetailResp = sysUserService.add(sysUserAddReq);
    
        // 存sys_aksk_user
        SysAkskUserPO po = new SysAkskUserPO();
        BeanUtils.copyProperties(req, po);
        long id = IdWorker.getId();
        po.setId(id);
        po.setUserId(sysUserDetailResp.getId());
        save(po);
        return queryDetail ? detail(id) : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAkskUserDetailRespVO delete(Long id) {
        Objects.requireNonNull(id, "id cannot be null.");
        SysAkskUserDetailRespVO resp = detail(id);
        Objects.requireNonNull(resp, "resp cannot be null.");
        removeById(id);
        sysUserService.delete(resp.getUserId(), true);
        return resp;
    }

    @Nullable
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysAkskUserDetailRespVO update(SysAkskUserUpdateReqVO req) {
        Long id = req.getId();
        String tenant = req.getTenant();
        String accessKey = req.getAccessKey();
        String secretKey = req.getSecretKey();
        String orgName = req.getOrgName();
        Long userId = getOne(new LambdaQueryWrapper<SysAkskUserPO>()
                .select(SysAkskUserPO::getUserId)
                .eq(SysAkskUserPO::getId, id)
        ).getUserId();
        // 改sys_user
        SysUserUpdateReqVO sysUserUpdateReq = new SysUserUpdateReqVO();
        sysUserUpdateReq.setId(userId);
        sysUserUpdateReq.setTenant(tenant);
        sysUserUpdateReq.setAccountNo(accessKey);
        sysUserUpdateReq.setPassword(secretKey);
        sysUserUpdateReq.setName(orgName);
        sysUserService.update(sysUserUpdateReq);
    
        // 改sys_aksk_user
        SysAkskUserPO po = new SysAkskUserPO();
        BeanUtils.copyProperties(req, po);
        updateById(po);
        return detail(id);
    }

    @Nullable
    @Override
    public SysAkskUserDetailRespVO detail(Long id) {
        Objects.requireNonNull(id, "id cannot be null.");
        SysAkskUserPO po = getById(id);
        if (po == null) {
            return null;
        }
        SysAkskUserDetailRespVO resp = new SysAkskUserDetailRespVO();
        BeanUtils.copyProperties(po, resp);
        
        // 查询sys_user
        SysUserDetailRespVO sysUserDetailResp = sysUserService.detail(po.getUserId());
        resp.setType(sysUserDetailResp.getType());
        resp.setTenant(sysUserDetailResp.getTenant());
        resp.setTenantName(sysUserDetailResp.getTenantName());
        resp.setRoleIds(sysUserDetailResp.getRoleIds());
        return resp;
    }
    
    @Override
    public PageInfo<SysAkskUserListRespVO> list(SysAkskUserListReqVO req) {
        int pageNum = req.getPageNum();
        int pageSize = req.getPageSize();
        Long userId = req.getUserId();
        String accessKey = req.getAccessKey();
        String orgName = req.getOrgName();

        // 分页查
        IPage<SysAkskUserPO> pageInfo = new Page<>(pageNum, pageSize);
        IPage<SysAkskUserPO> page = this.baseMapper.selectPage(pageInfo,
                new LambdaQueryWrapper<SysAkskUserPO>()
            .eq(userId != null,  SysAkskUserPO::getUserId, userId)
            .like(accessKey != null,  SysAkskUserPO::getAccessKey, accessKey)
            .like(orgName != null && orgName.trim().length() != 0,  SysAkskUserPO::getOrgName, orgName)
            .orderByDesc(SysAkskUserPO::getId)
        );
        // 转换为resp模型
        List<SysAkskUserPO> records = page.getRecords();
        List<SysAkskUserListRespVO> list;
        if (CollectionUtils.isEmpty(records)) {
            list = Collections.emptyList();
        } else {
            list = records.stream().map(po -> {
                SysAkskUserListRespVO resp = new SysAkskUserListRespVO();
                BeanUtils.copyProperties(po, resp);
                return resp;
            }).collect(Collectors.toList());
        }
        return PageInfo.of(page.getTotal(), pageNum, pageSize, list);
    }
}
